<?php
include_once '/var/www/html/new/com.inc.php';
include_once '/var/www/html/new/d/class/abc/PFTCoreAPI.class.php';

// 1.直销与转分销处理在同一个页面
// 2.直销只有PID，其他参数 lvl sourceid aids sid 都为空

$pid = $_REQUEST["pid"]+0;// 产品ID
$aid = $_REQUEST['sid']+0;// 供应商ID
if ($_REQUEST['auth'] == 'admin') {
	$_SESSION = $_REQUEST['session'];

}
if(!isset($_SESSION['sid'])) Response('fail', '登陆过期，请登录后配置');


$ac = $GLOBALS['_ac'];
$pw = $GLOBALS['_pw'];
$s  = new SoapClient(null,array("location" => "http://localhost/open/openService/pft_insideMX.php","uri" => "www.16u.com?ac_16u=$ac|pw_16u=$pw|auth_16u=true"));



$dist_list_a = array_keys($_REQUEST["pri"]);// 分销商ID数组
$dist_list_s = implode(',', $dist_list_a);
$dist_list_l = count($dist_list_a);
if($dist_list_l==0) Response('success', '配置成功');


$memberSID = $_SESSION['sid'];
$uupaid = $aid ? $memberSID:0;


// 获取会员自己的结算价
$pStorage = PFTCoreAPI::pStorage($s,$_SESSION['saccount'], $pid, $aid, date('Y-m-d'), 0);
$priSelf  = $pStorage['js']['p'];
if($priSelf==-1) Response('fail', '无权分销商该产品');

// 获取原配置分销差价
$sql   = "select dprice,pid,id from uu_priceset where aid=$uupaid and tid=$pid and pid in ($dist_list_s)";
$GLOBALS['le']->query($sql);
while($row=$GLOBALS['le']->fetch_assoc()) $dprice_a[$row['pid']] = $row;

if($_SESSION['sid']==38390){
	include_once '/var/www/html/new/d/a/1.php';
	exit;
}

// 开始设置分销差价
$ins_f  = false;
$sqlBox = array();
$insSql = "insert into uu_priceset (tid,pid,aid,dprice) values ";
$price_list = array_filter($_REQUEST['pri']);
foreach($price_list as $dist_mid=>$price){
	
	if($dist_mid==$_SESSION['sid']) continue;

	if (intval($price) >= 10000) {
		Response('fail', "价格配置必须限制在10000以内");
	}
	
	if(($diff = ($price-$priSelf)*100)<0){
		$sql = "select dname from pft_member where id=$dist_mid limit 1";
		$GLOBALS['le']->query($sql);
		$GLOBALS['le']->fetch_assoc();
		$dist_dname = $GLOBALS['le']->f('dname');
		Response('fail', "给分销商 $dist_dname 分销价配置错误");
	}
	
	if(isset($dprice_a[$dist_mid])){// 存在已经配置的记录
		if($dprice_a[$dist_mid]['dprice']==$diff) continue;
		$table_id = $dprice_a[$dist_mid]['id'];
		$sqlBox[] = "update uu_priceset set dprice=$diff where id=$table_id and aid=$uupaid and tid=$pid limit 1";
		continue;
	}
	
	$ins_f	= true;
	$insSql.= "($pid,$dist_mid,$uupaid,$diff),";
}

if($ins_f) $sqlBox[] = rtrim($insSql, ',');

if(count($sqlBox)){
	foreach($sqlBox as $sql) write_logs($GLOBALS['le']->query($sql).':'.$sql);
}




$sqlBox = array();
if($uupaid==0){// 直销配置
	$sqlBox_2 = array();
	// 获取记录  pft_product_sale_list
	$sql = "select * from pft_product_sale_list where aid=$memberSID and fid in ($dist_list_s) limit $dist_list_l";
	$GLOBALS['le']->query($sql);
	while($row=$GLOBALS['le']->fetch_assoc()) $direct[$row['fid']] = $row;
	foreach($dist_list_a as $dist_mid){
		
		$pids_a = explode(',', $direct[$dist_mid]['pids']);
		if($_REQUEST['pri'][$dist_mid]==''){// 价格为空去除分销权限
			if($pids_a[0]=='' || $pids_a[0]=='A') continue;
			if(!in_array($pid, $pids_a)) continue;
			$sqlBox_2[] = EvoSetStatus_1($pid, $dist_mid, $memberSID);
			$pids_a = array_diff($pids_a, array($pid));
		}else{
			if($pids_a[0]=='A') continue;
			if(in_array($pid, $pids_a)) continue;
			$pids_a[] = $pid;
		}
		$pids_s   = implode(',', array_filter(array_unique($pids_a)));

		if(!isset($direct[$dist_mid]['id'])) { 
			Response('fail', '请联系技术');
		};
		
		$sqlBox[] = "update pft_product_sale_list set pids='$pids_s' where id=".$direct[$dist_mid]['id']." and aid=$memberSID limit 1";
		
		// 更改开启转供应的按钮状态
		$sql = "select id from pft_p_apply_evolute where sid=$memberSID and fid=$dist_mid and pid=$pid and active=1 limit 1";
		$GLOBALS['le']->query($sql);
		if(!$GLOBALS['le']->fetch_assoc()) continue;
		$eid = $GLOBALS['le']->f('id');
		$sqlBox[] = "update pft_p_apply_evolute set active=0 where id=$eid limit 1";
	}
		
}else{
	
	// 获取会员的供应链   pft_p_apply_evolute
	$sql = "select id,aids,lvl,sourceid from pft_p_apply_evolute where sid=$aid and fid=$memberSID and pid=$pid and active=1 limit 1";
	$GLOBALS['le']->query($sql);
	$dbData  = $GLOBALS['le']->fetch_assoc();
	if($dbData){
		$chain_a = explode(',', $dbData['aids']);
		$chain_n = $dbData['aids'].','.$memberSID;
		$evo_lvl = count($chain_a) + 1;

		// 获取已设置的记录
		$evolute = array();
		$sql = "select id,aids,lvl,status,fid,aids from `pft_p_apply_evolute` where sid=$memberSID and pid=$pid and fid in ($dist_list_s) limit $dist_list_l";
		$GLOBALS['le']->query($sql);
		while($row=$GLOBALS['le']->fetch_assoc()) $evolute[$row['fid']] = $row;

		// 设置分销商购买权限
		$ins_f  = false;
		$insSql = "insert into pft_p_apply_evolute (sid,fid,sourceid,pid,lvl,status,aids,rectime) values ";
		foreach($dist_list_a as $dist_mid){
			
			if($dist_mid==$_SESSION['sid'] || in_array($dist_mid, $chain_a)) continue;// 去掉供应链上的分销商

			if(isset($evolute[$dist_mid])){// 存在之前设置过的记录
				$evolute_t = $evolute[$dist_mid];
				if($_REQUEST['pri'][$dist_mid]==''){// 价格为空去除分销权限
					if($evolute_t['status']==1) continue;
					$set_status_1[] = $evolute_t['id'];
					$sqlBox_2[] = EvoSetStatus_1($pid, $dist_mid, $evolute_t['aids'].','.$dist_mid);
					continue;
				}
				if(($_REQUEST['pri'][$dist_mid]-$priSelf)<0) continue;// 设置的价格比自己还小
				if($evolute_t['status']==0 && $evolute_t['aids']==$chain_n && $evolute_t['lvl']==$evo_lvl) continue;
				$upd_ids_a[] = $evolute_t['id'];continue;
			}
			
			if($_REQUEST['pri'][$dist_mid]=='') continue;
			if(($_REQUEST['pri'][$dist_mid]-$priSelf)<0) continue;
			
			$ins_f  = true;// 新增
			$insSql.= "($memberSID,$dist_mid,{$dbData['sourceid']},$pid,$evo_lvl, 0, '$chain_n', now()),";
		}

		if($ins_f) $sqlBox[] = rtrim($insSql, ',');

		// 更新状态
		if(($upd_ids_l = count($upd_ids_a))){
			$upd_ids_s = implode(',', $upd_ids_a);
			$sqlBox[] = "update pft_p_apply_evolute set status=0,aids='$chain_n',lvl=$evo_lvl where id in($upd_ids_s) and sid=$memberSID limit $upd_ids_l";
		}
		// 去除权限
		if(count($set_status_1)){
			$set_status_1 = implode(',', $set_status_1);
			$sqlBox[] = "update pft_p_apply_evolute set status=1,active=0 where id in($set_status_1) and sid=$memberSID";
		}
	}
	
}
if(count($sqlBox)){
	foreach($sqlBox as $sql) write_logs($GLOBALS['le']->query($sql).':'.$sql);
}



if(count($sqlBox)){
	if(count($sqlBox_2)) $sqlBox_2 = array_filter($sqlBox_2);
	if(count($sqlBox_2)) foreach($sqlBox_2 as $sql) write_logs($GLOBALS['le']->query($sql).':'.$sql);
}

Response('success', '配置成功');

function Response($status, $msg, $t='json'){
	if($t=='json') exit('{"status":"'.$status.'","msg":"'.$msg.'"}');
	exit("<script>alert('$msg');</script>");
}

function write_logs($txt,$file=''){
	if($file=='') $file = '/var/www/html/new/d/abc/logs/adjusting_'.$_SESSION['sid'].date('_Y-m-d').'.txt';
	$fp = fopen($file,"a");
	flock($fp, LOCK_EX);
	fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
	flock($fp, LOCK_UN);
	fclose($fp);
}


function EvoSetStatus_1($pid, $dist_mid, $aids=''){
	$evolist  = RecvEvoluteRow($pid, $dist_mid, $aids);
	$sql = '';
	if(count($evolist)){
		$ch_upd_ids = array();
		$detect = array();
		$detect_data = array();
		foreach($evolist as $key=>$row){
			if($row['status']==0) $ch_upd_ids[] = $row['id'];
		}
		if(count($ch_upd_ids)){
			$sql = "update pft_p_apply_evolute set status=1,active=0 where id in (".implode(',', $ch_upd_ids).") and pid=$pid limit ".count($ch_upd_ids);
		}
	}
	return $sql;
}

//  递归获取树形产品供应链
function RecvEvoluteRow($pid, $sid, $aids=''){
	
	$container = array();
	$sql = "select * from pft_p_apply_evolute where pid=$pid and sid=$sid and status=0";
	if($aids!='') $sql = $sql." and aids='$aids'";
	// echo $sql;
	$GLOBALS['le']->query($sql);
	while($row=$GLOBALS['le']->fetch_assoc()){
		$container[] = $row;
	}
	// print_r($container);
	if(count($container)){
		foreach($container as $row){
			$container = array_merge($container, RecvEvoluteRow($pid, $row['fid'], $row['aids'].','.$row['fid']));
		}
	}
	return $container;
}